package com.dinfo.shiro.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class MyRealm implements Realm {

	@Override
	public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {
		
		String username  = (String)token.getPrincipal();
		String passwd = new String( (char[])token.getCredentials());
		
		if(!"song".equals(username))
		{
			System.out.println("error  username!");
		}
		
		if(!"123".equals(passwd))
		{
			System.out.println("error passwd");
		}
		return new SimpleAuthenticationInfo(username, passwd ,getName());
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "myrealm";
	}

	@Override
	public boolean supports(AuthenticationToken toke) {
		// TODO Auto-generated method stub
		return toke instanceof UsernamePasswordToken;
	}
	
	
	
	
	public static void main(String[] args) {
		// 获取SecurityManager 的工厂 此处用的ini
        Factory<org.apache.shiro.mgt.SecurityManager> factory =  new  IniSecurityManagerFactory("shiro-realm.ini");
        // 得到SecurityManager 并且绑定到 SecurityUtils
        org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        
        Subject subject  =  SecurityUtils.getSubject();
        
        UsernamePasswordToken token = new UsernamePasswordToken("song", "123");
        
        try {
			subject.login(token);
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        System.out.println(subject.isAuthenticated());

	}
}
